package value

import (
	"reflect"
	"reflect_fast/model"
	"reflect_fast/utils"
)

type ReflectValue struct {
	val   reflect.Value
	model *model.Model
}

func (v *ReflectValue) SetValue(newVal any) error {
	err := utils.ValidateValueTyp(newVal)
	if err != nil {
		return err
	}
	newValue := reflect.ValueOf(newVal).Elem()

	for _, fieldName := range v.model.Fields {
		val := newValue.FieldByName(fieldName)
		fd := v.val.FieldByName(fieldName)
		if fd.CanSet() {
			fd.Set(val)
		}
	}
	return nil
}

var _ Value = (*ReflectValue)(nil)

func ReflectCreator(val any, model *model.Model) (Value, error) {
	err := utils.ValidateValueTyp(val)
	if err != nil {
		return nil, err
	}
	return &ReflectValue{val: reflect.ValueOf(val).Elem(), model: model}, nil
}

var _ Creator = ReflectCreator
